package cqrtplm.client;

import cqrtplm.config.SapApiConfig;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

@Component
public class SapApiClient {

    //@Autowired
    //private SapApiConfig sapConfig;

    private final OkHttpClient httpClient;
    private final SapApiConfig sapConfig;

    public SapApiClient(SapApiConfig sapConfig) {
        this.sapConfig = sapConfig;
        // 配置共享的OkHttpClient实例
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 调用 SAP API (支持泛型返回类型)
     *
     * @param factoryId 工厂ID (1000, 1200, 2500)
     * @param endpoint 接口端点(后半截接口地址)
     * @param jsonPayload 请求内容
     * @return SAP响应对象
     */
    public String callSapApi(String factoryId, String endpoint, String jsonPayload) {
        SapApiConfig.FactoryConfig config = sapConfig.getConfigForFactory(factoryId);

        try {
            // 1. 构建请求
            Request httpRequest = buildRequest(config, endpoint, jsonPayload);

            // 2. 发送请求
            Response response = httpClient.newCall(httpRequest).execute();

            // 3. 处理响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new SapApiException("SAP接口调用失败: " + e.getMessage(), e);
        }
    }

    /**
     * 构建 HTTP 请求
     */
    private Request buildRequest(SapApiConfig.FactoryConfig config, String endpoint, String jsonPayload){
        // 构建完整URL
        String fullUrl = buildFullUrl(config.getUrl(), endpoint);

        // 序列化请求体
        RequestBody body = RequestBody.create(jsonPayload, MediaType.parse("application/json"));

        // 创建认证头
        String authHeader = createBasicAuth(config.getUserName(), config.getPassword());

        return new Request.Builder()
                .url(fullUrl)
                .addHeader("Authorization", authHeader)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
    }

    /**
     * 处理 HTTP 响应
     */
    private String handleResponse(Response response) throws IOException {
        if (!response.isSuccessful()) {
            throw new SapApiException("SAP接口返回错误: " + response.code() + " - " + response.message());
        }

        ResponseBody body = response.body();
        if (body == null) {
            throw new SapApiException("SAP接口返回空响应体");
        }

        return body.string();
        //return responseBody;
    }

    /**
     * 构建完整URL
     */
    private String buildFullUrl(String baseUrl, String endpoint) {
        if (baseUrl.endsWith("/") && endpoint.startsWith("/")) {
            return baseUrl + endpoint.substring(1);
        }
        if (!baseUrl.endsWith("/") && !endpoint.startsWith("/")) {
            return baseUrl + "/" + endpoint;
        }
        return baseUrl + endpoint;
    }

    /**
     * 创建Basic认证头
     */
    private String createBasicAuth(String username, String password) {
        String credentials = username + ":" + password;
        byte[] encoded = Base64.getEncoder().encode(credentials.getBytes(StandardCharsets.UTF_8));
        return "Basic " + new String(encoded);
    }

    /**
     * SAP接口异常类
     */
    public static class SapApiException extends RuntimeException {
        public SapApiException(String message) {
            super(message);
        }

        public SapApiException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}